# 用户登录
from rest_framework.views import APIView
from utils.config import Config
from utils.oss.file_oss import FileOSS
from utils.result import R
from utils.aliverify_code import * 
from api.models import ItEduCollectLesson, ItEduLessonVideo,ItEduCommentLesson,ItEduLessonWatchLog,ItEduThumbLesson,ItEduVideoLink,ItEduLessonVideoSet,ItEduLessonOrder
from utils.util import Util
from django.utils import timezone  
from datetime import timedelta  

"""
视频详情页面
"""
class VideoAPIView(APIView):

    """
    单个视频详情页面数据获取
    """
    def get(self,request,*args, **kwargs):

        user_pk = request.session.get("user_pk")
        video_id = int(request.GET.get("video_id"))

        video = ItEduLessonVideo.objects.get(pk=video_id)
        
        # 计算该视频播放了多少次
        video_look_times = ItEduLessonWatchLog.objects.filter(lesson=video).count()
        # 评论的次数
        comment_num = ItEduCommentLesson.objects.filter(lesson=video).count()
        # 点赞次数
        like_num = ItEduThumbLesson.objects.filter(lesson=video,operate="1").count()
        # 点踩的次数
        dislike_num = ItEduThumbLesson.objects.filter(lesson=video,operate="-1").count()
        # 访问的URL
        url_list = list(ItEduVideoLink.objects.filter(user___id=user_pk,video=video).values("url","expired","createtime","_id"))
        url_expired_id = []
        video_url = ""
        for url in url_list:
            expired = url["expired"]
            create_time = url["createtime"]
            now_time = timezone.now()
            expired_time = create_time + timedelta(seconds=expired)
            if now_time >= expired_time:
                url_expired_id.append(url["_id"])
            else:
                video_url = url["url"]
                break 
        
        if not video_url:
            video_info = Util.str2json(video.matedata)
            # 判断用户是否可以获取该视频的链接（需要购买或者是VIP，即权限）
            auth = self.__video_url_auth(user_pk,video)
            if not auth:
                video_url = "default_url"
            else:
                # 获取链接的有效时长
                expired = video.duration * 2 
                video_url = FileOSS(video.save_type).get_url(video_info["key"],expired)
                _ = ItEduVideoLink.objects.create(
                    user___id = user_pk,
                    video = video,
                    url = video_url,
                    expired = expired
                )

        if len(url_expired_id) > 0:
            ItEduVideoLink.objects.filter(pk__in=url_expired_id).delete()

        # 添加用户访问 查看视频的日志记录   该记录为 视频播放次数
        _ = ItEduLessonWatchLog.objects.create(user___id=user_pk,lesson=video)

        video = {
            "title":video.title,
            "video_look_times":video_look_times,
            "createtime":video.createtime,
            "comment_num":comment_num,
            "like_num":like_num,
            "dislike_num":dislike_num,
            "tags":video.tags,
            "desc":video.intro,
            "_id":video._id,
            "url":video_url ,
        }

        return R().data_result(video=video)

    """
    获取视频集中的视频用于显示
    """
    def put(self,request,*args, **kwargs):
        lesson_set_id = request.data.get("lesson_set_id") 

        lesson_set = ItEduLessonVideoSet.objects.get(pk=lesson_set_id)
        video_id_list = lesson_set.lesson_order.split(",")

        video_list = []

        video_temp_list = ItEduLessonVideo.objects.filter(pk__in=video_id_list).values(
            "face_image",
            "_id",
            "title"
            )
        
        for video_id in video_id_list:
            for item in video_temp_list:
                if item["_id"] == video_id:
                    video_list.append(item)
                    break
    
        return R().data_result(video_list=video_list)
    
    """
    视频集推荐
    """
    def post(self,request,*args, **kwargs):

        tags = request.data.get("tags")
        tag_list = tags.split(",")

        recommend_lesson = list(ItEduLessonVideoSet.objects.filter(tags__contains=tag_list,score__get=Config.MIN_SHOW_LESSON_SET_SCORE).order_by("-score","-_id")[:5].values(
            "face_image",
            "_id",
            "title",
            "brand",
            "author__nickname"
        ))

        for lesson in recommend_lesson:
            lesson["join_user_num"] = ItEduCollectLesson.objects.filter(lesson_set___id=lesson["_id"]).count()

        return R().data_result(recommend_lesson = recommend_lesson)
            
    # 判断用户是否可以获取该视频的链接（需要购买或者是VIP，即权限）
    def __video_url_auth(self,user_pk,video):

        video_id = video._id
        lesson:ItEduLessonVideoSet = video.lesson_set
        video_id_list = lesson.lesson_order.split(",")

        if len(video_id_list) <= 3:
            return True 
        
        if video_id in video_id_list[0:3]:
            return True 
        
        # 判断视频集是否需要付费
        if lesson.price == 0:
            return True 
        
        # 用户是否购买对应的视频集
        buy = ItEduLessonOrder.objects.filter(user___id=user_pk,lesson=lesson).count() == 1

        return buy 
        
